package com.gepengjun.lims.config.redis;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.gepengjun.lims.config.shiro.KickoutSessionControlFilter;
import com.gepengjun.lims.entity.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;

import java.nio.charset.Charset;

public class FastJsonRedisSerializer<T> implements RedisSerializer<T> {

    private static final Logger logger = LoggerFactory.getLogger(FastJsonRedisSerializer.class);

    private static final Charset DEFAULT_CHARSET = Charset.forName("utf-8");

    private Class<T> clazz;

    public FastJsonRedisSerializer(Class<T> clazz) {
        super();
        this.clazz = clazz;
    }

    @Override
    public byte[] serialize(T t) throws SerializationException {
        if (null == t){
            return new byte[0];
        }
        logger.info("FastJsonRedisSerializer.serialize:t.getClass().getName():"+t.getClass().getName());
        return JSON.toJSONString(t,SerializerFeature.WriteClassName,SerializerFeature.WriteMapNullValue).getBytes(DEFAULT_CHARSET);
    }

    @Override
    public T deserialize(byte[] bytes) throws SerializationException {
        if (bytes == null || bytes.length <= 0){
            return null;
        }

        String string = new String(bytes,DEFAULT_CHARSET);
        logger.info("FastJsonRedisSerializer.deserialize:string:"+string);
        logger.info("FastJsonRedisSerializer.deserialize:JSON.parseObject(string,clazz).getClass().getName():"
                +JSON.parseObject(string,clazz).getClass().getName());
        return JSON.parseObject(string,clazz);

    }
}
